package com.zbb.exam_system.controller;

import com.alibaba.fastjson.JSON;

import com.zbb.exam_system.bean.JwtOperation;
import com.zbb.exam_system.constant.Method;
import com.zbb.exam_system.dto.JsonResult;
import com.zbb.exam_system.dto.UserDto;
import com.zbb.exam_system.entity.Modelpage;
import com.zbb.exam_system.service.ModelpageService;
import com.zbb.exam_system.service.UserService;
import com.zbb.exam_system.utils.ExamUtils;
import com.zbb.exam_system.utils.HttpUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.zbb.exam_system.constant.BusinessConstant.*;


/**
 * @author zbbstart
 * @date 2021/1/30 - 21:21
 */
@RestController
@RequestMapping("examSystem")
@Api(tags = "考试系统相关功能的接口")
public class MenuController {
    @Autowired
    private JwtOperation jwtOperation;
    @Autowired
    private UserService userService;
    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private ExamUtils examUtils;
    @Autowired
    private ModelpageService modelpageService;

    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER','ROLE_STUDENT')")
    @GetMapping("menus")
    @ApiOperation(value = "获取所有的菜单功能", notes = "当用户登录到达主页面时就会请求该链接渲染出所有的菜单功能")
    public JsonResult getMenuList(@ApiParam(name = "token", example = "") @RequestHeader("auth-token") String token, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            //获取所有的页面资源信息
            List<Modelpage> modelpages = modelpageService.getAllModelpages();
            //获取Claims
            Claims claims = jwtOperation.parseJwt(token);
            //获取用户信息
            UserDto user = JSON.parseObject(String.valueOf(claims.get("user")), UserDto.class);
            List<String> roles = user.getRoles();
            //管理员
            if (roles.contains("ROLE_ADMIN")){
                modelpages = modelpages.stream().filter(m -> !(EXAM_INFO.equals(m.getMenuName()))).collect(Collectors.toList());
            }
            //老师
            if ((roles.contains("ROLE_TEACHER")) && !(roles.contains("ROLE_ADMIN"))) {
                modelpages = modelpages.stream().filter(m -> !(TEACHER_MANAGER.equals(m.getMenuName()) || EXAM_INFO.equals(m.getMenuName()))).collect(Collectors.toList());
            }
            //学生
            if (!(roles.contains("ROLE_TEACHER")) && !(roles.contains("ROLE_ADMIN"))) {
                modelpages = modelpages.stream().filter(m -> !(TEACHER_MANAGER.equals(m.getMenuName()) || STUDENT_MANAGER.equals(m.getMenuName()))).collect(Collectors.toList());
            }
            modelpages.forEach(m -> m.setHtml(""));
            result = httpUtils.buildSuccess(Method.GET, modelpages);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 获取修改密码界面
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER','ROLE_STUDENT')")
    @GetMapping("pwd")
    @ApiOperation(value = "获取修改密码功能", notes = "当用户登录到达主页面时就会请求该链接渲染出修改密码功能")
    public JsonResult updatePwdMenu() {
        return httpUtils.buildSuccess(Method.GET, examUtils.getModelpage(UPDATE_PWD));
    }

    /**
     * 获取教师管理界面
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("teacher")
    @ApiOperation(value = "获取教师管理功能", notes = "当用户登录到达主页面时就会请求该链接渲染出教师管理功能")
    public JsonResult teacherManager() {
        return httpUtils.buildSuccess(Method.GET, examUtils.getModelpage(TEACHER_MANAGER));
    }

    /**
     * 获取学生管理界面
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @GetMapping("student")
    @ApiOperation(value = "获取学生管理功能", notes = "当用户登录到达主页面时就会请求该链接渲染出学生管理功能")
    public JsonResult studentManager() {
        return httpUtils.buildSuccess(Method.GET, examUtils.getModelpage(STUDENT_MANAGER));
    }
    /**
     * 获取题目管理界面
     */
    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_TEACHER')")
    @GetMapping("question")
    @ApiOperation(value = "获取题目管理功能", notes = "当用户登录到达主页面时就会请求该链接渲染出题目管理功能")
    public JsonResult questionManager() {
        return httpUtils.buildSuccess(Method.GET, examUtils.getModelpage(QUESTION_MANAGER));
    }
    /**
     * 获取试卷管理界面
     */
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    @GetMapping("paper")
    @ApiOperation(value = "获取试卷管理功能", notes = "当用户登录到达主页面时就会请求该链接渲染出试卷管理功能")
    public JsonResult paperManager(@RequestHeader("auth-token") String token) {
        JsonResult result = new JsonResult();
        UserDto userDto = userService.getUserInfoByToken(token);
        if (userDto.getRoles().contains("ROLE_ADMIN")){
            result = httpUtils.build403();
        }else{
            result =  httpUtils.buildSuccess(Method.GET, examUtils.getModelpage(PAPER_MANAGER));
        }
        return result;
    }
    /**
     * 获取考试信息界面
     */
    @PreAuthorize("hasRole('ROLE_STUDENT')")
    @GetMapping("info")
    @ApiOperation(value = "获取考试信息功能", notes = "当用户登录到达主页面时就会请求该链接渲染出考试信息功能")
    public JsonResult examManager() {
        return httpUtils.buildSuccess(Method.GET, examUtils.getModelpage(EXAM_INFO));
    }
}
